import datetime
import sys
import traceback

from fastapi import APIRouter
from re_common.baselibrary.utils.core.mdeprecated import try_except2_async

from apps.allsubdb.test.models import Test
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import ReturnInfo, SUCCESS, InputInfoModel
from apps.sql_app.mmongodb import Coll

router = APIRouter(route_class=ContextIncludedRoute)  #


@router.get("/strings")
async def down_wanfangqklist():
    """
    以a到z 请求json 获取列表
    :param proxy:
    :param rawid:
    :param page:
    :return:
    """
    return_info = ReturnInfo()
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "test"
    return_info.data = {"test1": "test2", "test3": "test4"}
    return return_info.todict()


@router.post("/test_error")
async def down_wanfangqklist(input: InputInfoModel[Test]):
    """
    以a到z 请求json 获取列表
    :param proxy:
    :param rawid:
    :param page:
    :return:
    """
    return_info = ReturnInfo()
    a = 1 / 0
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "test"
    return_info.data = {"test1": "test2", "test3": "test4"}
    return return_info.todict()


async def all_client_back_callback(*args, **kwargs):
    """
        处理返回值 确定是否进行存储
    :param self:
    :return:
    """
    from app_main import request_ctx_var
    from main import app
    from apps.file_uploadfile.models import ServerErrModel
    try_his = request_ctx_var.get().state.try_his
    try_his.append(traceback.format_exc())
    request = request_ctx_var.get()
    m = ServerErrModel().dict()
    m["ip_port"] = app.state.ip + ":" + str(app.state.port)
    m["client_ip"] = str(request.client.host)
    m["write_time"] = str(datetime.datetime.now())
    m["request_url"] = str(request.url)
    # https://github.com/tiangolo/fastapi/issues/1216 作者目前还没有解决这个bug
    # m.request_body = body.decode()
    m["request_body"] = str(request.state.mbody)
    m["err_type"] = str(sys.exc_info()[0])
    m["err_msg"] = str(sys.exc_info()[1])
    m["traceback_str"] = traceback.format_exc()
    save_dicts = ServerErrModel.parse_obj(m)
    m_result = Coll.get_server_exception()
    result = await m_result.insert_one(save_dicts.dict(by_alias=True))
    exception_list = ["proxy"]
    for i in exception_list:
        if i in traceback.format_exc():
            return False, {"traceback": traceback.format_exc(), "need_save": False}
    return False, {"traceback": traceback.format_exc(), "need_save": True}


@try_except2_async(callback=all_client_back_callback, is_print=True)
async def test():
    a = 1 / 0
    return True, ""


@router.post("/test_error_get")
async def down_wanfangqklist(input: InputInfoModel[Test]):
    """
    修改测试装饰器用
    :param proxy:test
    :param rawid:
    :param page:
    :return:
    """
    return_info = ReturnInfo()
    # a = 1 / 0
    bools, err = await test()
    print(bools)
    print(err)
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "test"
    return_info.data = {"test1": "test2", "test3": "test4"}
    return return_info.todict()


@router.get("/return_none")
async def down_wanfangqklist():
    pass
